package com.wutuo.aggragation.institution.controller;

import cn.apestar.agg.common.security.ticket.TicketConfig;
import cn.apestar.agg.institution.controller.InstitutionController;
import cn.apestar.cloud.api.SysImageAPIService;
import cn.apestar.cloud.api.enums.ImageTypeEnum;
import cn.apestar.core.base.BaseMessage;
import cn.apestar.core.framework.cache.CacheTemplate;
import cn.apestar.user.provider.institution.cache.InstitutionCacheProvider;
import com.wutuo.institution.api.InstitutionWTAPIService;
import com.wutuo.institution.api.request.InstitutionWTRequest;
import com.wutuo.school.api.SchoolAPIService;
import com.wutuo.school.api.request.SchoolRequest;
import com.wutuo.school.provider.domain.School;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * Created by Singer_YDW on 2016/11/9.
 */
@RestController @RequestMapping(value = {"/institution"}, produces = {"application/json"})
public class InstitutionWTController extends InstitutionController {

    @Autowired private HttpServletRequest request;

    @Autowired private CacheTemplate cacheTemplate;

    @Autowired @Qualifier("institutionWTService") private InstitutionWTAPIService institutionService;

    @Autowired private InstitutionCacheProvider institutionCacheProvider;

    @Autowired private SysImageAPIService sysImageService;

    @Autowired private SchoolAPIService schoolService;

    /**
     * 新增机构
     *
     * @param institution
     */
    @RequestMapping(value = "/addOrUpdate", method = RequestMethod.POST) public Object create(
            @RequestBody @Valid InstitutionWTRequest institution) {

        if (institution.getId() != null) {

            institutionCacheProvider.deleteCache(institution.getId());
        }

        if (institution.getUserId() == null) {

            institution.setUserId(getCurrentUserId());
        }

        if (institution.getUserId() == null) {

            institution.setUserId(getCurrentUserId());
        }
        // 获取机构中学校列表
        List<SchoolRequest> schools = institution.getSchools();
        if (schools != null) {
            // 获取学校IDs
            String schoolIdsStr = "";
            for (SchoolRequest school : schools) {
                if (school == null)
                    continue;
                // 判断是否已包含学校ID
                School findSchool = schoolService.getSchoolByCreateBy(school.getBaiduId());
                // 判断学校数据库中是否包含该学校
                if (findSchool == null) {
                    // 添加到学校数据库
                    school.setCity(institution.getCity());
                    school.setProvince(institution.getProvince());
                    school.setCounty(institution.getCounty());
                    school.setRemarks(school.getBaiduId());
                    schoolService.addorUpdate(school);
                } else {
                    school.setId(findSchool.getId());
                }
                // 添加到机构字符串中
                if (StringUtils.isNotEmpty(schoolIdsStr)) {
                    schoolIdsStr += ",";
                }
                schoolIdsStr += school.getId();
                institution.setSchoolId(schoolIdsStr);
            }
        }
        // 保存机构
        institutionService.addorUpdate(institution);

        return new BaseMessage();
    }

    /**
     * 获取机构-详细
     *
     * @param id
     */
    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
    public Object getInstitutionByAllDetailId(@PathVariable("id") Long id) {

        return institutionService.getInstitutionByAllDetailId(id, getCurrentUserId());
    }

    /**
     * 查询机构
     *
     * @param id
     * @return
     */
    @Override @RequestMapping(value = "/clearCache/{id}", method = RequestMethod.GET)
    public Object lisForPage(@PathVariable("id") Long id) {

        institutionCacheProvider.deleteCache(id);

        sysImageService.deletePl(id, ImageTypeEnum.INSTITUTION_IMAGE.getValue());
        return new BaseMessage();
    }

    /**
     * 查询机构
     *
     * @return
     */
    @RequestMapping(value = "/initCache", method = RequestMethod.GET) public Object initCache() {

        institutionService.initCache();
        return new BaseMessage();
    }

    public Long getCurrentUserId() {

        String ticket = request.getHeader("ticket");
        String userId = cacheTemplate.valueGet(TicketConfig.KEY_TKUSER + ticket, String.class);
        return userId == null ? null : Long.valueOf(userId);
    }
}
